package com.lly.pro.controller;

import com.lly.pro.common.*;
import com.lly.pro.entity.Admin;
import com.lly.pro.entity.HR;
import com.lly.pro.entity.User;
import com.lly.pro.service.AdminService;
import com.lly.pro.service.HRService;
import com.lly.pro.service.UserService;
import com.xiaoleilu.hutool.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Hommond
 * @date 2/22/2019
 */
@Controller
public class LoginController {

    private static final Logger log = Logger.getLogger(LoginController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private HRService hrService;

    @PostMapping(value = "/login")
    @ResponseBody
    public ResponseJson login(@RequestBody JSONObject param,HttpServletRequest request){
        log.info("登录---------param："+param);
        //检查参数是否齐全
        if (!ParamterCheckUtil.isLoginParamComplete(param)){
            return ResponseJsonUtil.getErrorResult(ResponseStatusCodes.MISSING_PARAMETERS,"缺少参数或参数错误");
        }

        //获取参数
        HttpSession session = request.getSession();
        Long userId = param.getLong("userId");
        String password = param.getStr("password");
        String identity = param.getStr("identity");

        if (isUserExist(userId,password,identity)){
            session.setAttribute("userId",userId);
            return ResponseJsonUtil.SUCCESS_WITH_NO_DATA;
        }else{
            return ResponseJsonUtil.getErrorResult(ResponseStatusCodes.USER_NON_EXISTENT,"用户不存在");
        }


    }


    /**
     * 判断用户是否存在
     * @Param ls 用户列表
     * @return
     */
    private boolean isUserExist(Long userId,String password,String identity){
        if(identity.equals(Identity.EMPLOYEE)){
            return userService.findByUserIdAndPassword(userId,password)==1L;

        }else if (identity.equals(Identity.HR)){
            return hrService.findByUserIdAndPassword(userId,password)==1L;

        }else if (identity.equals(Identity.ADMIN)){
            return adminService.findByUserIdAndPassword(userId,password)==1L;

        }else{
            return false;
        }
    }

}
